package ArrayAndString;

import java.util.Arrays;

public class CompressString {
    private int[] func(int num){
        int count = 0, numCopy = num;
        while(numCopy> 0){
            count++;
            numCopy /= 10;
        }
        int[] arr = new int[count];
        while(num > 0){
            arr[--count] = num % 10;
            num /= 10;
        }
        return arr;
    }
    public int compress(char[] chars) {
        if(chars.length == 1){
            return 1;
        }
        int left = 0,right = 1,count = 0,index = 0,available = 0,k = 1;
        while(right < chars.length){
            k = 1;
            while(right < chars.length && chars[right] == chars[left]){
                right++;
                k++;
            }
            chars[index++] = chars[left];
            available++;
            if(k > 9){
                int[] arr = func(k);
                for(int i = 0 ; i < arr.length ; i++){
                    chars[index++] = (char) (arr[i] + '0');
                }
                available += arr.length;
            }else if(k > 1 && k <= 9){
                chars[index++] = (char) ((k) + '0');
                available++;
            }

            left = right ;
            right = right + 1;
            if(left == chars.length -1){
                chars[index++] = chars[left];
                available++;
            }
        }
        return available;
    }
}
